package com.yyk.yiliao.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.listener.DialogSureCancelListenter;
import com.yyk.yiliao.listener.OneValueListenter;

import com.yyk.yiliao.ui.trade.AddBankcardActivity;

import com.yyk.yiliao.ui.trade.minepwd.FindInvestPasswordActivity;
import com.yyk.yiliao.ui.trade.widget.OnPasswordInputFinish;
import com.yyk.yiliao.ui.trade.widget.PasswordView2;
import com.yyk.yiliao.ui.trade.widget.PhoneSmsView;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.UserbankMybankcardInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by ${zk} on 2018/8/21 0021.
 */

public class DialogUtil {
    private static DialogUtil yuanShengDialogUtil;

    private DialogUtil() {

    }

    public static DialogUtil getIntanse() {
        //双重判断+ 同步线程锁
        if (yuanShengDialogUtil == null) {
            synchronized (DialogUtil.class) {
                if (yuanShengDialogUtil == null)
                    yuanShengDialogUtil = new DialogUtil();
            }
        }
        return yuanShengDialogUtil;
    }

    public interface AlertDialogListenter {
        void queding();

        void quxiao();
    }

    /**
     * 显示提示消息的对话框
     *
     * @param context 上下文
     * @param title   对话框标题
     * @param message 对话框提示内容
     * @return
     * @author codingblock 2015-8-11
     */
    public AlertDialog simpleDialog(final Context context, String title, String message, String positive, String negative, final AlertDialogListenter listenter) {
        AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(positive, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listenter.queding();

                    }
                })
                .setNegativeButton(negative, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listenter.quxiao();
                    }
                }).create();

        return dialog;
    }


    /**
     * 性别选择框
     */
    private String[] sexArry = new String[]{"女", "男"};// 性别选择

    public void showSexChooseDialog(Context context, final OneValueListenter listenter) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);// 自定义对话框
        builder.setSingleChoiceItems(sexArry, -1, new DialogInterface.OnClickListener() {// 2默认的选中
            @Override
            public void onClick(DialogInterface dialog, int which) {// which是被选中的位置
                // showToast(which+"");
                listenter.onClickListenter(sexArry[which]);
                dialog.dismiss();// 随便点击一个item消失对话框，不用点击确认取消
            }
        });
        builder.show();// 让弹出框显示
    }


    /**
     * 原生提示框
     * <p>
     * 不需要返回的时候  true 外部不能点击
     */
    public void showReturnTips(Context context, String title, String message, String sureTitle, String cancelTitle, final DialogSureCancelListenter listenter, boolean flag) {
        final AlertDialog alertDialog = new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(sureTitle, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listenter.onSureListenter();

                    }
                })
                .setNegativeButton(cancelTitle, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listenter.onCancelListenter();

                    }
                }).create();
        if (flag) {
            alertDialog.setCanceledOnTouchOutside(false);//          即可实现点击外部不消失。
// 在弹出的时候禁止使用返回键
            alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (alertDialog != null && alertDialog.isShowing()) {
                        return true;
                    }
                    return false;
                }
            });
        }
        alertDialog.show();
        // TODO  两个按钮颜色
//        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(0xff6191F4);
//        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(0xff6191F4);
//        return alertDialog;
    }

    /**
     * 自定义dialog宽度全屏 - CSDN博客  https://blog.csdn.net/yshr1991/article/details/52353854
     * 从底部吐出dialog
     * 支付交易码  体现
     */
    public interface PayListenter {
        void onClick(String password, AlertDialog dialog, TextView textView);
    }

    public void showPayDialog(Context context, PayListenter listenter) {
            /* 创建AlertDialog对象并显示 */
        final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.MyDialog).create();
        alertDialog.show();
                        /* 添加对话框自定义布局 */
        alertDialog.setContentView(R.layout.alertdialog_popwindow_pay2);
    /* 获取对话框窗口 */
        Window window = alertDialog.getWindow();
//        /* 设置显示窗口的宽高 */
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        /* 设置窗口显示位置 */
        window.setGravity(Gravity.BOTTOM);
/*       将对话框的大小按屏幕大小的百分比设置
*/
        WindowManager windowManager = ((Activity) context).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
//        lp.height = (int) (display.getHeight() * 0.6); //设置高度
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT; //设置高度
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; //设置宽度
        alertDialog.getWindow().setAttributes(lp);
        window.getDecorView().setPadding(0, 0, 0, 0);
        /* 还可以设置窗口显示动画 */
        window.setWindowAnimations(R.style.mystyle);
        /* 通过window找布局里的控件 */
        //取消dialog以外的区域的点击事件（默认为true）这里我们设置成false就ok啦
        alertDialog.setCanceledOnTouchOutside(false);

        //初始化控件
        PasswordView2 pwdView = window.findViewById(R.id.pwd_view);
        // 添加回调接口
        pwdView.setOnFinishInput(new OnPasswordInputFinish() {
            @Override
            public void inputFinish() {


            }

            @Override
            public void inputFinish(TextView cuowutishi) {

                // 输入完成后我们简单显示一下输入的密码
                // 也就是说——>实现你的交易逻辑什么的在这里写
//                Toast.makeText(context, pwdView.getStrPassword(),
//                        Toast.LENGTH_SHORT).show();
                listenter.onClick(pwdView.getStrPassword(), alertDialog, cuowutishi);


            }

            //取消支付
            @Override
            public void outfo() {
                //关闭支付页面
                DialogUtil.getIntanse().simpleDialog(context, "", "确定退出吗？", "确定", "取消", new DialogUtil.AlertDialogListenter() {
                    @Override
                    public void queding() {
                        // 隐藏对话框
                        alertDialog.dismiss();

                    }

                    @Override
                    public void quxiao() {

                    }
                }).show();
            }

            //忘记密码回调事件
            @Override
            public void forgetPwd() {
                // 隐藏对话框
                alertDialog.dismiss();
//                ToastUtil.showShort(null, "忘记密码");
                Intent intent = new Intent(context, FindInvestPasswordActivity.class);
                context.startActivity(intent);

            }
        });
        //返回监听
        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // 防止  up 和 down事件 执行两次
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (alertDialog != null && alertDialog.isShowing()) {
                        //关闭支付页面
                        final AlertDialog backDialog = DialogUtil.getIntanse().simpleDialog(context, "", "确定退出吗？", "确定", "取消", new AlertDialogListenter() {
                            @Override
                            public void queding() {
                                // 隐藏对话框
                                alertDialog.dismiss();

                            }

                            @Override
                            public void quxiao() {

                            }
                        });
                        backDialog.show();
                    }
                    return true;
                }
                return false;

            }
        });
    }


    /**
     * 充值 需要 手机验证码   可以用回调
     * 1.点击支付
     * 2.设置手机号和自动获取验证码
     * 3.请求验证码
     * 4.手动获取验证码
     */
    public interface RechargeListenter {
        void onClick(String password, AlertDialog dialog);

        void onTextPhone(TextView textView, TextView textView2);

        void postHttp();

        void sendSms(TextView sms);
    }

    public void showPhoneSmsDialog(Context context, RechargeListenter listenter) {
            /* 创建AlertDialog对象并显示 */
        final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.MyDialog).create();
        alertDialog.show();
                        /* 添加对话框自定义布局 */
        alertDialog.setContentView(R.layout.alertdialog_popwindow_phonesms);


         /* 获取对话框窗口 */
        Window window = alertDialog.getWindow();
       /* 设置显示窗口的宽高 */
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        /* 设置窗口显示位置 */
        window.setGravity(Gravity.BOTTOM);
        /*       将对话框的大小按屏幕大小的百分比设置*/
        WindowManager windowManager = ((Activity) context).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
//        lp.height = (int) (display.getHeight() * 0.7); //设置高度
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT; //设置高度
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; //设置宽度
        alertDialog.getWindow().setAttributes(lp);
        window.getDecorView().setPadding(0, 0, 0, 0);
        /* 还可以设置窗口显示动画 */
        window.setWindowAnimations(R.style.mystyle);
        alertDialog.setCanceledOnTouchOutside(false);

        //初始化控件
        PhoneSmsView smsView = window.findViewById(R.id.phone_sms);
        TextView tvBankel = smsView.findViewById(R.id.tv_bankel);
        TextView tvHqsms = smsView.findViewById(R.id.tv_hqsms);

        listenter.onTextPhone(tvBankel, tvHqsms);

        // 添加回调接口n
        smsView.setOnFinishInput(new OnPasswordInputFinish() {
            @Override
            public void inputFinish() {
                // 输入完成后我们简单显示一下输入的密码
                // 也就是说——>实现你的交易逻辑什么的在这里写
//                ToastUtil.showShort(null, "确认支付" + smsView.getStrPassword());
                listenter.onClick(smsView.getStrPassword(), alertDialog);


            }

            @Override
            public void inputFinish(TextView cuowutishi) {

            }

            //取消支付
            @Override
            public void outfo() {
                //关闭支付页面
                DialogUtil.getIntanse().simpleDialog(context, "", "确定退出吗？", "确定", "取消", new DialogUtil.AlertDialogListenter() {
                    @Override
                    public void queding() {
                        // 隐藏对话框
                        alertDialog.dismiss();
                    }

                    @Override
                    public void quxiao() {

                    }
                }).show();
            }

            //获取验证码
            @Override
            public void forgetPwd() {
                listenter.sendSms(tvHqsms);


            }
        });
        listenter.postHttp();


        //返回监听
        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // 防止  up 和 down事件 执行两次
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (alertDialog != null && alertDialog.isShowing()) {
                        //关闭支付页面
                        final AlertDialog backDialog = DialogUtil.getIntanse().simpleDialog(context, "", "确定退出吗？", "确定", "取消", new AlertDialogListenter() {
                            @Override
                            public void queding() {
                                // 隐藏对话框
                                alertDialog.dismiss();

                            }

                            @Override
                            public void quxiao() {

                            }
                        });
                        backDialog.show();
                    }
                    return true;
                }
                return false;

            }
        });
    }

    /**
     * 自定义dialog宽度全屏 - CSDN博客  https://blog.csdn.net/yshr1991/article/details/52353854
     * 选择支付方式  提现 有微信和支付宝
     */
    //1.照片.2.支付名字3.方式id,4.银行预留手机号奥马，5.dismms
    public interface SelectPayListenter {
        void onClick(String img, String name, String id, String phone, AlertDialog dialog);
    }

    private List<UserbankMybankcardInfo.DataBean> list = new ArrayList<>();
    private BaseRecyclerAdapter<UserbankMybankcardInfo.DataBean> adapter;

    public void showPayFangshiDialog(Context context, boolean flag, boolean wxzfbFlag, SelectPayListenter listenter) {
            /* 创建AlertDialog对象并显示 */
        final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.MyDialog).create();
        alertDialog.show();
                        /* 添加对话框自定义布局 */
        alertDialog.setContentView(R.layout.alertdialog_popwindow_pay);
        //外部不能点击
        alertDialog.setCanceledOnTouchOutside(false);

    /* 获取对话框窗口 */
        Window window = alertDialog.getWindow();
//        /* 设置显示窗口的宽高 */
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        /* 设置窗口显示位置 */
        window.setGravity(Gravity.BOTTOM);
/*       将对话框的大小按屏幕大小的百分比设置
*/
        WindowManager windowManager = ((Activity) context).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
        lp.height = (int) (display.getHeight() * 0.6); //设置高度
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; //设置宽度
        alertDialog.getWindow().setAttributes(lp);
        window.getDecorView().setPadding(0, 0, 0, 0);
        /* 还可以设置窗口显示动画 */
        window.setWindowAnimations(R.style.mystyle);
        /* 通过window找布局里的控件 */
        LinearLayout ll_zfb = window.findViewById(R.id.ll_zfb);
        LinearLayout ll_wx = window.findViewById(R.id.ll_wx);
        LinearLayout ll_addcard = window.findViewById(R.id.ll_addcard);

        if (wxzfbFlag) {
            ll_zfb.setVisibility(View.GONE);
            ll_wx.setVisibility(View.GONE);
        } else {
            ll_zfb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listenter.onClick(String.valueOf(R.mipmap.icon_zfbb), "支付宝支付", "1", "", alertDialog);
                }
            });
            ll_wx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listenter.onClick(String.valueOf(R.mipmap.icon_wxx), "微信支付", "2", "", alertDialog);
                }
            });
        }
        ll_addcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, AddBankcardActivity.class));
                alertDialog.dismiss();
            }
        });
        window.findViewById(R.id.iv_close).
                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 隐藏对话框
                        alertDialog.dismiss();
                    }
                });


        RecyclerView recyclerView = window.findViewById(R.id.rv_cardlist);
        Map<String, String> map = new TreeMap<>();
        map.put("id", Hawk.get("uid") + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postUserbankMybankcard(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<UserbankMybankcardInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(UserbankMybankcardInfo info) {
                        Logger.e("我的银行卡列表" + info.toString());
                        if (flag) {
                            list.clear();
                        }
                        if (info.getCode() == 1) {
                            if (info.getData().size() > 0 && info.getData() != null) {
                                list.addAll(info.getData());
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                });

        //银行卡列表
        adapter = new BaseRecyclerAdapter<UserbankMybankcardInfo.DataBean>(context, list, R.layout.adapter_item_mypayfangshi) {
            @Override
            public void convert(BaseRecyclerHolder holder, UserbankMybankcardInfo.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.tv_cardtype_name, item.getBank_name() + " (尾数" + item.getNumberu() + ")");
                holder.setImageByUrl(R.id.iv_img, ApiService.BASE_URL + item.getImg());
            }
        };
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Bundle bundle = new Bundle();
                int id = list.get(position).getBindid();
                int cardtype = list.get(position).getCardtype();
                String img = list.get(position).getImg();
                String name = list.get(position).getBank_name();
                String numberu = list.get(position).getNumberu();
                String banktel = "验证码已发送手机号" + list.get(position).getBanktel(); //银行预留手机号
                bundle.putString("id", id + "");
                bundle.putString("cardtype", cardtype + "");
                bundle.putString("img", img + "");
                bundle.putString("name", name + "");
                bundle.putString("numberu", numberu + "");
                listenter.onClick(img, name + " (尾数" + numberu + ")", String.valueOf(id), banktel, alertDialog);

            }
        });

    }

//

}
